/**
 * @author DongPing
 * 2022/2/18 17:29
 *
 * 收款-业务认领-支付指令
 *
 * */
import {useContext, useEffect, useRef, useState} from "react";
import {IClaimItemsBusinessProps, IClaimItemsProps} from "@/biz-components/claim-items/IClaimItemsProps";
import {CommonTable} from "@/biz-components/claim-items/components-v2/CommonTable";
import {CellInput, CommonFilter, CommonFilterItem, FilterFunctions} from "../components-v2";
import ClaimItemsDataUtil from "@/biz-components/claim-items/ClaimItemsDataUtil";
import {DetailContext} from "@/biz-components/claim-items/components/DetailContext";
import {useField} from "@formily/react";
import {Field} from "@formily/core/lib/models";
import {getAllTypesOfMetasByPageCode} from "@/biz-components/claim-items/components";
//import moment from "moment";
import { plus } from '@ey-utils/utils/numberPrecision';
import {xhrPostJson} from "@/services";
import {SelectDays} from "@/biz-components/claim-items/collection-business-instruct/SelectDays";
import {daysFilter} from "@/biz-components/claim-items/collection-business-instruct/days-filter";
import * as CommonDataSource from '@/common-data-source';
import {SelectInvoiceType} from "@/biz-components/claim-items/collection-business-instruct/SelectInvoiceType";



//  查询认领明细数据
function queryClaimItems (params: IClaimItemsBusinessProps, filterObj: any): Promise<any[]> {
	const {shop = '', journalAccount = ''} = params;
	return xhrPostJson('/asm/claimDetail/bizClaimByPymtInstList', {
		companyCode: shop,
		bankStmtCode: journalAccount,
		payDateDay: filterObj.applyDate,
		refCode: filterObj.bizCode,
		refType: filterObj.bizType
	})
		.then((res: any) => {
			return ClaimItemsDataUtil.setTempId(res.result || []);
		})
	// let mockData = [
	// 	{cllctDetail: `t1-${matchType}-${shop}-${claimTarget}`, code: '232432'},
	// 	{cllctDetail: `t2-${matchType}-${shop}-${claimTarget}`, code: 'ab32', applyDate: '2022-02-25'},
	// ]
	// return Promise.resolve(ClaimItemsDataUtil.setTempId(mockData));
}

// export function getDefaultDateRange(): [string, string] {
// 	const mBefore = moment().subtract(7, 'days').format('YYYY-MM-DD');
// 	const mNow = moment().format('YYYY-MM-DD');
// 	return [mBefore, mNow];
// }

const PAGE_CODE = 'ClaimInfoA_Pymt_IT_L';

export function CollectionBusinessInstruct(props: IClaimItemsProps) {

	const [metaArr, setMetaArr] = useState<any[]>([]);
	const {value = []} = props;
	useEffect(function () {
		getAllTypesOfMetasByPageCode(PAGE_CODE)
			.then((data) => {
				setMetaArr(data.tableColumnMetas)
			})
	}, []);

	const validateTableRef = useRef<() => boolean>(null);
	/**
	 * 日期范围选择项的初始值
	 * */
	const [initialDays,  setInitialDays] = useState<string | null>(null);
	useEffect(function () {
		CommonDataSource.dictionary.queryDictionaryForSelect('CLAIM_PYMT_INST_PAY_DATE')
			.then((data) => {
				setInitialDays(data.length > 0 ? data[0].value : '');
			})
			.catch(() => {
				setInitialDays('');
			})
	}, []);

	const getCurrentFilterObjectRef = useRef<() => any>(null);

	/**
	 * 开始查询数据
	 * */
	function queryData() {
		const filterData = getCurrentFilterObjectRef.current ? getCurrentFilterObjectRef.current() : {};
		queryClaimItems(props, filterData)
			.then((data) => {
				props.onChange(data);
			})
	}
	/**
	 * 过滤器数据变化的时候，将上一次查询到的数据过滤
	 * */
	function onFilterChange() {
		queryData();
	}

	useEffect(() => {
		if(props.queryClaimItemsFlag > 0) {
			if(initialDays === null) {
				setTimeout(queryData, 1000);
			} else {
				queryData();
			}

		}
	}, [props.queryClaimItemsFlag]);

	const detailMode = useContext(DetailContext);

	const field = useField<Field>();
	useEffect(function () {
		if(!detailMode) {
			field.setValidator(() => {
				if(!value.some((item) => item.__checked)) {
					return {type: 'error', message: '请选择认领明细'}
				}
				if(validateTableRef.current && !validateTableRef.current()) {
					return {type: 'error', message: '认领明细填写有误'}
				} else {
					return null;
				}
			})
		}
		return function () {
			field.setValidator(() => true);
		}
	}, [field, detailMode, validateTableRef, value]);

	function onCheckChange(record: object | null, checked: any) {
		value.forEach((item) => {
			if((record === null) || (record === item)) {
				item.__checked = checked;
				item.thisClaimAmt = checked ? item.billAmt : '';
			}
		});
		props.onChange([...value]);
	}

	const filterFunctionRef = useRef<any>(null);

	if(initialDays === null) {
		return null;
	}

	return (
		<div>
			{
				!detailMode && (
					<CommonFilter metaArr={metaArr} filterFunctionRef={filterFunctionRef} getCurrentFilterObjectRef={getCurrentFilterObjectRef} onChange={onFilterChange}>
						<CommonFilterItem name={'bizCode'} Component={[CellInput.TextInput, {}]} filterFunction={FilterFunctions.stringLike}/>
						<CommonFilterItem initialValue={initialDays ? Number(initialDays) : null} name={'applyDate'} Component={[SelectDays, {}]} filterFunction={daysFilter}/>
						<CommonFilterItem name={'bizType'} Component={[SelectInvoiceType, {}]} filterFunction={FilterFunctions.stringEqual}/>
					</CommonFilter>
				)
			}
			<CommonTable
				pageCode={PAGE_CODE}
				metaArr={metaArr}
				value={props.value}
				onChange={props.onChange}
				detailMode={detailMode}
				claimItemsInvalid={true}
				validateFunctionRef={validateTableRef}
				checkOperation
				onCheckChange={onCheckChange}
				columnsOptionArr={[
					{
						name: 'thisClaimAmt',
						component: [CellInput.NumberInput, {}],
						validator: (v, record) => {
							if(!record.__checked) return true;
							return Number(v) > 0;
						},
						onRowChange: (row: any) => {
							row.billAmt = row.thisClaimAmt;
						},
						disabled: true
					}
				]}
			/>
		</div>
	)
}
CollectionBusinessInstruct.calcTotalAmt = function (data: any[]) {
	let total = 0;
	for(const item of data) {
		if(item.__checked) {
			let n = Number(item.thisClaimAmt);
			total = plus(total, isNaN(n) ? 0 : n)
		}
	}
	return total;
}
CollectionBusinessInstruct.getCheckedValues = function (data: any[] = []) {
	return ClaimItemsDataUtil.removeTempId(data.filter((item) => {
		let valid = item.__checked === true;
		delete item.__checked;
		return valid;
	}))
}
